import { RbacUserRoleType } from '@/data/auth/admin';
import { RbacUserStatusValueEnum } from '@/enums/auth';
import { useRoles } from '@/hooks/auth/useRoles';
import { useTenants } from '@/hooks/auth/useTenants';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { ProFormGroup } from '@ant-design/pro-form/lib';
import React, { useRef, useState } from 'react';

const AddModal: React.FC<{
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: RbacUserRoleType) => Promise<void>;
}> = ({ visible, onCancel, onSubmit }) => {
  const { allRoles } = useRoles();
  const { allTenantValueEnum } = useTenants();
  const formRef = useRef<any>(null);

  const [roleOptions, setRoleOptions] = useState<any>([]);

  return (
    <ModalForm
      title="新建"
      width="800px"
      open={visible}
      onFinish={onSubmit}
      formRef={formRef}
      onOpenChange={(value) => {
        if (!value) onCancel();
      }}
    >
      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '租户为必填项',
            },
          ]}
          width="md"
          name="tenantId"
          label={'租户'}
          placeholder={'请选择租户'}
          valueEnum={allTenantValueEnum}
          onChange={(value) => {
            const roles = allRoles.filter((item: any) => item.tenantId === value);
            setRoleOptions(
              roles.map((role) => {
                return {
                  label: role.name,
                  value: role.id,
                };
              }),
            );
          }}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '密码为必填项',
            },
          ]}
          width="md"
          name="password"
          label={'密码'}
          placeholder={'请输入密码'}
        />
      </ProFormGroup>
      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormText
          rules={[
            {
              required: true,
              message: '用户名为必填项',
            },
          ]}
          width="md"
          name="username"
          label={'用户名'}
          placeholder={'请输入用户名'}
        />
        <ProFormText width="md" name="mobile" label={'手机号'} placeholder={'请输入手机号'} />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '至少选择一个角色',
            },
          ]}
          width="md"
          name="roles"
          label={'角色'}
          mode="multiple"
          options={roleOptions}
        />
        <ProFormSelect
          name="status"
          width="md"
          label={'状态'}
          valueEnum={RbacUserStatusValueEnum}
        />
        <ProFormTextArea width="md" name="remark" label={'备注'} placeholder={''} />
      </ProFormGroup>
    </ModalForm>
  );
};

export default AddModal;
